//给定一个二叉树，返回它的 后序 遍历。 
//
// 示例: 
//
// 输入: [1,null,2,3]  
//   1
//    \
//     2
//    /
//   3 
//
//输出: [3,2,1] 
//
// 进阶: 递归算法很简单，你可以通过迭代算法完成吗？ 
// Related Topics 栈 树 深度优先搜索 二叉树 
// 👍 725 👎 0

package leetcode.editor.cn;

import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

/**
 * [145]二叉树的后序遍历
 */
public class BinaryTreePostorderTraversal {
    public static void main(String[] args) {
        Solution solution = new BinaryTreePostorderTraversal().new Solution();
        TreeNode root = new BinaryTreePostorderTraversal().new TreeNode();
        root.val = 1;

        TreeNode node1 = new BinaryTreePostorderTraversal().new TreeNode();
        node1.val = 2;
        root.right = node1;

        TreeNode node2 = new BinaryTreePostorderTraversal().new TreeNode();
        node2.val = 3;
        node1.left = node2;

        List<Integer> result = solution.postorderTraversal(root);
        System.out.println("--end--");
    }
    //leetcode submit region begin(Prohibit modification and deletion)
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */

public class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;
    TreeNode() {}
    TreeNode(int val) { this.val = val; }
    TreeNode(int val, TreeNode left, TreeNode right) {
        this.val = val;
        this.left = left;
        this.right = right;
    }
}

class Solution {
    public List<Integer> postorderTraversal(TreeNode root) {
        List<Integer> result = new ArrayList<>();
        Stack<TreeNode> stack = new Stack<>();
        TreeNode cur = root;
        TreeNode pre = cur;
        while (!stack.isEmpty() || cur != null) {
            if (cur != null) {
                stack.push(cur);
                pre = cur;
                cur = cur.left;
            } else {
                TreeNode temp = stack.peek();
                if (temp.right == null || temp.right == pre) {
                    result.add(temp.val);
                    pre = stack.pop();
                } else {
                    cur = temp.right;
                }
            }
        }
        return result;
    }
}
//leetcode submit region end(Prohibit modification and deletion)

}